<template>
  <div>
    <header
      style="
        display: flex;
        margin-bottom: -0.5%;
        justify-content: space-between;
      "
    >
      <h1>参数结果查询</h1>
    </header>
    <el-main
      style="
        display: flex;
        justify-content: center;
        align-items: center;
        flex-direction: column;
      "
    >
      <el-col style="width: 100%; margin-top: -1.5%; margin-bottom: 0.5%">
        <el-header>查询排序统计报表</el-header>
      </el-col>
      <div
        style="
          width: 60%;
          display: flex;
          justify-content: center;
          align-items: center;
        "
      >
        <a style="width: 140px; margin-right: -10px; font-size: 20px"
          >选择电路：</a
        >
        <el-select
          v-model="circuitName1"
          placeholder="请选择电路"
          size="large"
          style="width: 40%"
        >
          <el-option
            v-for="item in result"
            :key="item"
            :label="item"
            :value="item"
            @click="getName(item)"
          >
          </el-option>
        </el-select>
        <a style="width: 140px; margin: 0 -20px 0 10px; font-size: 20px"
          >列表大小：</a
        >
        <el-input
          size="large"
          v-model="limit"
          style="width: 30%; margin-left: 2%"
        ></el-input>
        <el-button
          type="primary"
          size="large"
          style="margin-left: 2%; background-color: #003f82"
          @click="fetchData"
          >查询统计报表
        </el-button>
        <el-button
          type="primary"
          size="large"
          style="background-color: #595959; margin-left: 2.5%"
          @click="reset"
          >重置
        </el-button>
      </div>

      <div style="width: 95%; display: flex; justify-content: center">
        <el-table
          :default-sort="{ prop: 'score__sum', order:'descending'}"
          max-height="400px"
          stripe
          border
          :data="tableData"
          style="margin-top: 10px"
        >
          <el-table-column type="index" label="序号" width="60">
            <template #default="{ $index }">
              {{ $index + 1 }}
            </template>
          </el-table-column>
          <el-table-column align="center" label="复制" width="60">
            <template #default="scope">
              <div
                style="
                  display: flex;
                  flex-direction: column;
                  justify-content: center;
                  align-items: center;
                "
              >
                <el-button
                  link
                  type="primary"
                  @click="copyToClipboard(scope.row)"
                  >复制</el-button
                >
              </div>
            </template>
          </el-table-column>
          <el-table-column align="center" label="操作" width="120">
            <template #default="scope">
              <div
                style="
                  display: flex;
                  flex-direction: column;
                  justify-content: center;
                  align-items: center;
                "
              >
                <el-button
                  icon="Edit"
                  link
                  type="primary"
                  @click="getErrorList(scope.row)"
                  >异常报表
                </el-button>
                <el-button
                  style="margin-left: 0"
                  icon="View"
                  link
                  type="primary"
                  @click="goToDetail(scope.row)"
                  >详情查询
                </el-button>
                <el-button
                  style="margin-left: 0"
                  icon="Help"
                  link
                  type="primary"
                  @click="goToDetailAI(scope.row)"
                  >人工调参
                </el-button>
              </div>
            </template>
          </el-table-column>
          <el-table-column
            sortable
            prop="score__sum"
            label="score__sum"
            align="center"
            width="200"
          ></el-table-column>
          <el-table-column
            sortable
            prop="score__vgh"
            label="score__vgh_margin"
            align="center"
            width="200"
          ></el-table-column>
          <el-table-column
            sortable
            prop="score__vth_neg"
            label="score__vth_neg_margin"
            align="center"
            width="200"
          ></el-table-column>
          <el-table-column
            sortable
            prop="score__vth_pos"
            label="score__vth_pos_margin"
            align="center"
            width="200"
          ></el-table-column>
          <el-table-column
            prop="A11"
            label="A11"
            align="center"
            width="180"
          ></el-table-column>
          <el-table-column
            prop="A21"
            label="A21"
            align="center"
            width="180"
          ></el-table-column>
          <el-table-column
            prop="A22"
            label="A22"
            align="center"
            width="180"
          ></el-table-column>
          <el-table-column
            prop="A32"
            label="A32"
            align="center"
            width="180"
          ></el-table-column>
          <el-table-column
            prop="A41"
            label="A41"
            align="center"
            width="180"
          ></el-table-column>
          <el-table-column
            prop="A42"
            label="A42"
            align="center"
            width="180"
          ></el-table-column>
          <el-table-column
            prop="A44"
            label="A44"
            align="center"
            width="180"
          ></el-table-column>
          <el-table-column
            prop="A51"
            label="A51"
            align="center"
            width="180"
          ></el-table-column>
          <el-table-column
            prop="A52"
            label="A52"
            align="center"
            width="180"
          ></el-table-column>
          <el-table-column
            prop="A53"
            label="A53"
            align="center"
            width="180"
          ></el-table-column>
          <el-table-column
            prop="A54"
            label="A54"
            align="center"
            width="180"
          ></el-table-column>
          <el-table-column
            prop="A55"
            label="A55"
            align="center"
            width="180"
          ></el-table-column>
          <el-table-column
            prop="A56"
            label="A56"
            align="center"
            width="180"
          ></el-table-column>
          <el-table-column
            prop="A72"
            label="A72"
            align="center"
            width="180"
          ></el-table-column>
          <el-table-column
            prop="Cb"
            label="Cb"
            align="center"
            width="180"
          ></el-table-column>
        </el-table>
      </div>
      <el-col style="width: 100%; margin-top: 10px">
        <el-card style="margin-top: 10px">
          <el-dialog
            v-model="isShowDarw"
            :before-close="handleClose"
            style="
              width: 85%;
              display: flex;
              flex-direction: column;
              margin-top: 3%;
            "
            :close-on-press-escape="false"
            custom-class="floating-window"
          >
            <div>
              <span>指定参数返回电路曲线图象</span>

              <el-scrollbar max-height="750px">
                <div
                  v-for="i in visiblePlotCount"
                  :key="i"
                  :id="'bokeh-plot' + i"
                ></div>
              </el-scrollbar>
            </div>
          </el-dialog>

          <!-- 最小化后的图标 -->
          <el-tooltip content="点击显示悬浮窗" placement="right">
            <el-button
              tabindex="9999"
              v-if="isMinimized"
              icon="el-icon-plus"
              @click="restoreWindow"
              class="button-tooltip"
            ></el-button>
          </el-tooltip>
          <el-header>
            <div style="display: flex; justify-content: space-between">
              获取指定解的未满足条件
              <div style="display: flex" v-if="isShowDarwButton">
                <!-- 下拉框选择画布 -->
                <el-select
                  style="width: 180px; margin-right: 10px"
                  v-model="selectedPlot"
                >
                  <el-option
                    v-for="i in visiblePlotCount"
                    :key="i"
                    :value="'plot' + i"
                    :label="'画布' + i"
                  ></el-option>
                </el-select>
                <!-- 增加画布选项 -->
                <el-button
                  type="primary"
                  @click="addPlotOption"
                  :disabled="visiblePlotCount >= 10"
                  style="background-color: #333333"
                  >增加画布
                </el-button>
                <el-button
                  type="primary"
                  @click="clearPlot"
                  style="background-color: #595959"
                  >清空画布
                </el-button>
              </div>
            </div>
          </el-header>
          <el-scrollbar
            max-height="600px"
            style="display: flex; justify-content: space-between"
          >
            <div class="flex-container">
              <div
                v-for="(value, key) in resposerErr"
                :key="key"
                class="flex-item"
              >
                <el-form>
                  <el-form-item>
                    <h2>{{ key }}</h2>
                  </el-form-item>
                  <el-form-item v-for="(val, index) in value" :key="index">
                    <h1>{{ `${index}:` }}</h1>
                    <strong style="margin-left: 10px; color: #003f82">{{
                      val
                    }}</strong>
                    <el-button
                      type="primary"
                      size="small"
                      @click="drawPlotWave(key, index)"
                      style="margin-left: 5px; background-color: #003f82"
                      >图示
                    </el-button>
                  </el-form-item>
                </el-form>
              </div>
            </div>
          </el-scrollbar>
        </el-card>
      </el-col>
    </el-main>
  </div>
</template>

<script setup name="参数结果查询">
import {
  watch,
  onActivated,
  nextTick,
  onMounted,
  onUnmounted,
  reactive,
  ref,
  defineProps,
} from "vue";

import { ElMessage } from "element-plus";
import { circuitServer } from "@/server/iIndex";
import {
  getPlotWave,
  getSingleEvalReport,
  getResultErrLs,
  getResultReport,
} from "@/server/results";
import router from "@/router/index.js";

const limit = ref(1);
const circuitName = ref("...");
const circuitName1 = ref("");
const results = ref([]);
const result = ref([]);
const reqData = ref({
  circuit_diagram_name: "",
  limit: limit.value,
});
const reset = () => {
  router.go(0);
};
const getName = (item) => {
  circuitName.value = item;

  console.log(circuitName.value);
};
const props = defineProps({
  rowData1: Object,
});
const getSingLeEvalReport = async () => {
  try {
    console.log(props);
    const response = await getSingleEvalReport(props.rowData1);
    if (response.状态||response.状态==="任务不存在"){
      confirm("任务不存在，请勿点击查看详情")
      router.back()
      return;
    }
    console.log(response);
    Object.keys(response).forEach((key) => {
      tableHeaders[key] = key;
      response[key].forEach((value, index) => {
        if (!tableData.value[index]) {
          tableData.value[index] = {};
        }
        tableData.value[index][key] = value;
      });
    });
  } catch (e) {
    console.log(e);
  }
};
const getCircuit = async () => {
  try {
    results.value = await circuitServer();
    result.value = results.value.name;
  } catch (error) {
    ElMessage.warning("获取电路失败");
  }
};

const tableData = ref([]);
let tableHeaders = reactive({});
const longData = ref([]);
watch(
  () => props.rowData1?.circuit_diagram_name,
  (newVal) => {
    if (newVal) {
      circuitName.value = newVal;
    }
    reqData.value.circuit_diagram_name = circuitName.value;
  },
  { immediate: true }
);

const fetchData = async () => {
  try {
    tableData.value = [];
    tableHeaders.value = {};
    // 请求数据时，始终使用 circuitName 作为 circuit_diagram_name
    reqData.value.circuit_diagram_name = circuitName.value;
    reqData.value.limit = limit.value;
    const response = await getResultReport(reqData.value);
    if (response.状态 && response.状态 == "无仿真结果") {
      console.log("无仿真结果");
      confirm("无仿真结果，请稍后再试");
    }
    Object.keys(response).forEach((key) => {
      tableHeaders[key] = key;
      response[key].forEach((value, index) => {
        if (!tableData.value[index]) {
          tableData.value[index] = {};
        }
        tableData.value[index][key] = value;
      });
    });
  } catch (error) {
    console.error("Error fetching data:", error);
  }
};

const rowData = ref({});
const resposerErr = ref({});
const getErrorList = async (row) => {
  console.log("点击了");
  try {
    setCircuitName();
    rowData.value = {
      circuit_diagram_name: circuitName2.value,
      A11: row.A11,
      A21: row.A21,
      A22: row.A22,
      A32: row.A32,
      A41: row.A41,
      A42: row.A42,
      A44: row.A44,
      A51: row.A51,
      A52: row.A52,
      A53: row.A53,
      A54: row.A54,
      A55: row.A55,
      A56: row.A56,
      A72: row.A72,
      Cb: row.Cb,
    };
    const response = await getResultErrLs(rowData.value);
    longData.value = response;
    resposerErr.value = response;
  } catch (e) {
    console.error("e:", e);
  }
};
// 定义一个响应式引用，用于存储Bokeh图表实例

const selectedPlot = ref("plot1");
const plots = ref({ plot1: ref(null), plot2: ref(null) }); // 初始化两个画布
const clearPlot = () => {
  // 弹出自定义对话框
  const userChoice = prompt(
    "请选择操作：\n1. 取消\n2. 清空选中画布\n3. 清空全部画布",
    "1"
  );

  // 根据用户选择执行相应操作
  switch (userChoice) {
    case "2": // 清空选中画布
      clearSelectedPlot();
      break;
    case "3": // 清空全部画布
      clearAllPlots();
      break;
    default: // 用户选择取消或其他
      return; // 不执行任何操作
  }
};

const clearSelectedPlot = () => {
  if (selectedPlot.value) {
    const plotId = selectedPlot.value;
    const plotElement = document.getElementById(
      `bokeh-plot${plotId.slice(-1)}`
    );
    if (plotElement) {
      plotElement.innerHTML = "";
    }
    // 重置选中的画布引用
    plots.value[plotId] = null;
  }
};

const clearAllPlots = () => {
  // 遍历plots对象中的所有画布
  for (const plotId in plots.value) {
    const plotElement = document.getElementById(
      `bokeh-plot${plotId.slice(-1)}`
    );
    if (plotElement) {
      plotElement.innerHTML = "";
    }
    // 重置画布引用
    plots.value[plotId] = null;
  }
  // 重置其他状态变量
  isMinimized.value = false;
  isShowDarw.value = false;
  visiblePlotCount.value = 2;
};
const draw_bokeh = (plot, all_data, plotIndex, color) => {
  const { voltage, time, title } = all_data;
  let show = false;
  if (!plot) {
    plot = window.Bokeh.Plotting.figure({
      title: title,
      x_axis_label: "时间",
      y_axis_label: "电压",
      tools: "pan,crosshair,wheel_zoom,box_zoom,reset,save",
      height: window.innerHeight / 3,
      width: (window.innerWidth / 5) * 4,
    });

    const { HoverTool } = window.Bokeh;
    const hover = new HoverTool({
      tooltips: [
        ["电压值", "@voltage"],
        ["时间", "@time"],
        ["名称", "@title"],
      ],
      mode: "mouse", // Hover mode
    });
    plot.add_tools(hover);
    show = true;
  }

  let titles = [];
  for (let i = 0; i < time.length; ++i) {
    titles.push(title);
  }

  const source = new window.Bokeh.ColumnDataSource({
    data: { time: time, voltage: voltage, title: titles },
  });

  // 添加曲线到图表
  plot.line(
    { field: "time" },
    { field: "voltage" },
    { source: source, line_width: 2, line_color: color }
  );

  // 渲染图表到页面
  if (show) {
    const plotElement = document.getElementById(`bokeh-plot${plotIndex}`);
    window.Bokeh.Plotting.show(plot, plotElement);
  }
  return plot;
};
const getRandomColor = () => {
  const letters = "0123456789ABCDEF";
  let color = "#";
  for (let i = 0; i < 6; i++) {
    color += letters[Math.floor(Math.random() * 16)];
  }

  return color;
};

const isShowDarwButton = ref(false);
const isShowDarw = ref(false);
const drawPlotWave = async (key, index) => {
  try {
    isMinimized.value = false;
    isShowDarw.value = true;
    isShowDarwButton.value = true;
    const plotIndex = selectedPlot.value.slice(-1);
    const response = await getPlotWave({
      ...rowData.value,
      type: key,
      line_info: `${index}`,
    });
    const color = getRandomColor();
    plots.value[selectedPlot.value] = draw_bokeh(
      plots.value[selectedPlot.value],
      response,
      plotIndex,
      color
    );
  } catch (e) {
    console.error("e:", e);
  }
};

const visiblePlotCount = ref(2); // 默认显示两个画布

const addPlotOption = () => {
  if (visiblePlotCount.value < 10) {
    const isconfirm = confirm("是否增加画布");
    if (isconfirm) {
      const newPlotId = `plot${visiblePlotCount.value + 1}`;
      plots.value[newPlotId] = ref(null); // 添加新的画布引用
      visiblePlotCount.value++;
    }
  }
};

const goToDetail = (row) => {
  const isConfirm = confirm("点击详情查询将会跳转另一页面，是否确认？");
  if (isConfirm) {
    setCircuitName();
    rowData.value = {
      circuit_diagram_name: circuitName2.value,
      A11: row.A11,
      A21: row.A21,
      A22: row.A22,
      A32: row.A32,
      A41: row.A41,
      A42: row.A42,
      A44: row.A44,
      A51: row.A51,
      A52: row.A52,
      A53: row.A53,
      A54: row.A54,
      A55: row.A55,
      A56: row.A56,
      A72: row.A72,
      Cb: row.Cb,
    };
    if (rowData.value == null) {
      confirm("请先选择查询统计报表");
      return;
    }
    router.push({
      name: "仿真类型查询",
      query: {
        rowData: JSON.stringify(rowData.value),
      },
    });
  }
};
const setCircuitName = () => {
    circuitName2.value = circuitName.value;
};
const circuitName2 = ref("");
const goToDetailAI = (row) => {
  const isConfirm = confirm("点击详情查询将会跳转另一页面，是否确认？");
  if (isConfirm) {
    setCircuitName();
    rowData.value = {
      circuit_diagram_name: circuitName2.value,
      A11: row.A11,
      A21: row.A21,
      A22: row.A22,
      A32: row.A32,
      A41: row.A41,
      A42: row.A42,
      A44: row.A44,
      A51: row.A51,
      A52: row.A52,
      A53: row.A53,
      A54: row.A54,
      A55: row.A55,
      A56: row.A56,
      A72: row.A72,
      Cb: row.Cb,
    };
    if (rowData.value == null) {
      confirm("请先选择查询统计报表");
      return;
    }
    router.push({
      name: "人工调参",
      query: {
        rowData: JSON.stringify(rowData.value),
      },
    });
  }
};

const isMinimized = ref(false);

function handleClose(done) {
  isMinimized.value = true;
  done();
}

function minimizeWindow() {
  isShowDarw.value = false;
  isMinimized.value = true;
}

function restoreWindow() {
  isShowDarw.value = true;
  isMinimized.value = false;
}

function handleGlobalClick(event) {
  console.log("被点击了：handleGlobalClick");
  const dialog = document.querySelector(".floating-window");
  if (isShowDarw.value && !dialog.contains(event.target)) {
    minimizeWindow();
  }
}

const copyToClipboard = (row) => {
  let textToCopy = "";

  // 处理特殊的.PARAM和Cb
  for (const [key, value] of Object.entries(row)) {
    if (key === "Cb") {
      textToCopy += `.PARAM ${key}=${value}\n\n`;
    } else if (key.startsWith("A")) {
      textToCopy += `.PARAM ${key}=${value}\n\n`;
    }
  }
  for (const [key, value] of Object.entries(row)) {
    if (!key.startsWith("A") && key !== "Cb" && !key.startsWith(".PARAM")) {
      textToCopy += `***${key} ${value}\n\n`;
    }
  }
  const textarea = document.createElement("textarea");
  textarea.value = textToCopy;
  document.body.appendChild(textarea);
  textarea.select();
  document.execCommand("copy");
  document.body.removeChild(textarea);

  ElMessage({
    message: "复制成功！",
    type: "success",
  });
};
onActivated(()=>{
  if (props.rowData1){
    if (props.rowData1.circuit_diagram_name!=circuitName.value) {
      tableData.value=[];
      tableHeaders.value={};
      limit.value = 1;
      circuitName1.value = circuitName.value;
      fetchData();
    }else {
      tableData.value=[];
      tableHeaders.value={};
      limit.value = 1;
      circuitName1.value = props.rowData1.circuit_diagram_name;
      getSingLeEvalReport();
    }
  }
})
onMounted(async () => {
  await nextTick(() => {
    const dialog = document.querySelector(".floating-window");
    if (dialog) {
      document.addEventListener("click", handleGlobalClick);
    }
  });

  getCircuit();
});
onUnmounted(() => {
  document.removeEventListener("click", handleGlobalClick);
});
</script>

<style lang="scss" scoped>
.button-tooltip{
    background-color: transparent;
    z-index: 9999;
    position: fixed;
    right: 5.5%;
    top: 55%;
    background-image: url('@/assets/xuanfuchaun.png');
    background-size: cover;
    background-repeat: no-repeat;
    border: none;
    width: 2.5%;
    height: 5%;
}
.flex-container {
  display: flex;
  flex-wrap: wrap;
  /* justify-content: space-between; */
}

.flex-column {
  flex: 1 1 100%;
  display: flex;
  flex-direction: column;
}

@font-face {
  font-family: "SimSun";
  src: url("src/assets/simsun.ttc") format("woff2");
}

.flex-item {
  margin: 10px;
}

.span-style {
  margin-top: -5px;
  margin-bottom: -2px;
  font-size: 18px;
}

.table-header {
  background-color: black;
}

.inputStyle {
  width: 850px;
}

table {
  div {
    cursor: pointer;
  }
}

header {
  padding: 20px;
  background-color: #f8f9fa;
}

main {
  margin-top: 20px;
}

footer {
  text-align: center;
  margin-top: 20px;
}

.el-divider {
  margin-top: 10px;
  margin-bottom: -10px;
}
</style>
